<template>
  <view class="work-order-create-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">{{ isEdit ? '编辑工单' : '创建工单' }}</text>
    </view>

    <!-- 基本信息 -->
    <view class="form-section">
      <view class="section-title">基本信息</view>

      <view class="form-item">
        <text class="form-label required">工单标题</text>
        <input
          v-model="formData.title"
          placeholder="请输入工单标题"
          class="form-input"
          :maxlength="100"
        />
      </view>

      <view class="form-item">
        <text class="form-label required">工单类型</text>
        <view class="radio-group">
          <view
            v-for="type in workOrderTypes"
            :key="type.value"
            class="radio-item"
            :class="{ active: formData.work_order_type === type.value }"
            @click="formData.work_order_type = type.value"
          >
            <text class="radio-text">{{ type.label }}</text>
          </view>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label required">优先级</text>
        <view class="radio-group">
          <view
            v-for="priority in priorities"
            :key="priority.value"
            class="radio-item priority"
            :class="{ active: formData.priority === priority.value }"
            @click="formData.priority = priority.value"
          >
            <view class="priority-dot" :class="priority.value"></view>
            <text class="radio-text">{{ priority.label }}</text>
          </view>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">问题描述</text>
        <textarea
          v-model="formData.description"
          placeholder="请详细描述问题或检查要求"
          class="form-textarea"
          :maxlength="1000"
          auto-height
        />
        <view class="char-count">{{ formData.description.length }}/1000</view>
      </view>
    </view>

    <!-- 设备信息 -->
    <view class="form-section">
      <view class="section-title">设备信息</view>

      <view class="form-item device-selector">
        <text class="form-label required">选择设备</text>
        <view class="device-select" @click="selectDevice">
          <view v-if="selectedDevice" class="selected-device">
            <text class="device-name">{{ selectedDevice.name }}</text>
            <text class="device-location">📍{{ selectedDevice.location }}</text>
          </view>
          <view v-else class="select-placeholder">
            <text class="placeholder-text">请选择设备</text>
            <text class="placeholder-icon">➤</text>
          </view>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">具体位置</text>
        <input
          v-model="formData.location"
          placeholder="请输入具体位置（可选）"
          class="form-input"
          :maxlength="100"
        />
      </view>
    </view>

    <!-- 检查清单（仅日常巡检类型显示）-->
    <view v-if="formData.work_order_type === 'inspection'" class="form-section">
      <view class="section-title">检查清单</view>
      <view class="inspection-checklist">
        <view
          v-for="(item, index) in inspectionChecklist"
          :key="index"
          class="checklist-item"
        >
          <view class="item-checkbox" @click="toggleChecklistItem(index)">
            <text class="checkbox-icon">{{ item.checked ? '☑' : '☐' }}</text>
          </view>
          <view class="item-content">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-desc">{{ item.description }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 预计信息 -->
    <view class="form-section">
      <view class="section-title">预计信息</view>

      <view class="form-item">
        <text class="form-label">预计工时</text>
        <view class="time-input-group">
          <input
            v-model.number="formData.estimated_duration"
            type="number"
            placeholder="30"
            class="form-input time-input"
          />
          <text class="time-unit">分钟</text>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">所需技能</text>
        <view class="tag-input-container">
          <view v-for="(skill, index) in formData.required_skills" :key="index" class="skill-tag">
            <text class="tag-text">{{ skill }}</text>
            <text class="tag-remove" @click="removeSkill(index)">×</text>
          </view>
          <input
            v-model="skillInput"
            placeholder="输入技能后按回车添加"
            class="skill-input"
            @confirm="addSkill"
          />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">所需物料</text>
        <view class="tag-input-container">
          <view v-for="(material, index) in formData.materials_needed" :key="index" class="material-tag">
            <text class="tag-text">{{ material }}</text>
            <text class="tag-remove" @click="removeMaterial(index)">×</text>
          </view>
          <input
            v-model="materialInput"
            placeholder="输入物料后按回车添加"
            class="material-input"
            @confirm="addMaterial"
          />
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="form-actions">
      <button
        class="btn btn-primary"
        @click="submitForm"
        :disabled="!isFormValid"
        :class="{ 'btn-disabled': !isFormValid }"
      >
        <text class="btn-text">{{ isEdit ? '保存修改' : '创建工单' }}</text>
      </button>
      <button
        class="btn btn-secondary"
        @click="cancelForm"
      >
        <text class="btn-text">取消</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 页面参数
const isEdit = ref(false)
const workOrderId = ref('')

// 表单数据
const formData = ref({
  title: '',
  description: '',
  work_order_type: 'maintenance',
  priority: 'medium',
  device_id: '',
  location: '',
  estimated_duration: 30,
  required_skills: [] as string[],
  materials_needed: [] as string[]
})

// 输入状态
const skillInput = ref('')
const materialInput = ref('')

// 选中设备
const selectedDevice = ref<any>(null)

// 工单类型选项
const workOrderTypes = ref([
  { label: '设备维护', value: 'maintenance' },
  { label: '故障维修', value: 'repair' },
  { label: '日常巡检', value: 'inspection' },
  { label: '设备安装', value: 'installation' },
  { label: '清洁服务', value: 'cleaning' }
])

// 优先级选项
const priorities = ref([
  { label: '紧急', value: 'urgent' },
  { label: '高', value: 'high' },
  { label: '中', value: 'medium' },
  { label: '低', value: 'low' }
])

// 检查清单（仅日常巡检）
const inspectionChecklist = ref([
  { name: '外观清洁度检查', description: '检查设备外观是否清洁', checked: true },
  { name: '门锁功能检查', description: '检查门锁是否正常开启和关闭', checked: true },
  { name: '照明系统检查', description: '检查内部照明是否正常', checked: true },
  { name: '洗手液余量检查', description: '检查洗手液分配器余量', checked: false },
  { name: '纸巾余量检查', description: '检查纸巾分配器余量', checked: false },
  { name: '水箱水位检查', description: '检查水箱水位是否正常', checked: false },
  { name: '异味检测', description: '检查内部是否有异常异味', checked: false },
  { name: '地面清洁度', description: '检查地面是否清洁干燥', checked: false }
])

// 表单验证
const isFormValid = computed(() => {
  return formData.value.title.trim() !== '' &&
         formData.value.work_order_type !== '' &&
         formData.value.priority !== '' &&
         formData.value.device_id !== ''
})

// 切换检查清单项目
const toggleChecklistItem = (index: number) => {
  inspectionChecklist.value[index].checked = !inspectionChecklist.value[index].checked
}

// 选择设备
const selectDevice = () => {
  uni.showActionSheet({
    itemList: ['移动厕所-001 - 人民广场东侧', '移动厕所-002 - 中央公园南门', '移动厕所-003 - 商业街北口'],
    success: (res) => {
      const deviceMap = [
        { id: '1', name: '移动厕所-001', location: '人民广场东侧' },
        { id: '2', name: '移动厕所-002', location: '中央公园南门' },
        { id: '3', name: '移动厕所-003', location: '商业街北口' }
      ]
      selectedDevice.value = deviceMap[res.tapIndex]
      formData.value.device_id = selectedDevice.value.id
    }
  })
}

// 添加技能
const addSkill = () => {
  const skill = skillInput.value.trim()
  if (skill && !formData.value.required_skills.includes(skill)) {
    formData.value.required_skills.push(skill)
    skillInput.value = ''
  }
}

// 移除技能
const removeSkill = (index: number) => {
  formData.value.required_skills.splice(index, 1)
}

// 添加物料
const addMaterial = () => {
  const material = materialInput.value.trim()
  if (material && !formData.value.materials_needed.includes(material)) {
    formData.value.materials_needed.push(material)
    materialInput.value = ''
  }
}

// 移除物料
const removeMaterial = (index: number) => {
  formData.value.materials_needed.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  if (!isFormValid.value) {
    uni.showToast({
      title: '请填写必填项',
      icon: 'none'
    })
    return
  }

  uni.showLoading({ title: isEdit.value ? '保存中...' : '创建中...' })

  try {
    // 构建提交数据
    const submitData = {
      ...formData.value,
      // 如果是日常巡检，添加检查清单到描述中
      ...(formData.value.work_order_type === 'inspection' && {
        description: `${formData.value.description}\n\n检查清单：\n${inspectionChecklist.value
          .filter(item => item.checked)
          .map(item => `✓ ${item.name}：${item.description}`)
          .join('\n')}`
      })
    }

    console.log('提交数据：', submitData)

    // 模拟API调用
    setTimeout(() => {
      uni.hideLoading()
      uni.showToast({
        title: isEdit.value ? '保存成功' : '创建成功',
        icon: 'success'
      })

      // 返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }, 2000)

  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    })
  }
}

// 取消表单
const cancelForm = () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消' + (isEdit.value ? '编辑' : '创建') + '吗？未保存的数据将丢失。',
    success: (res) => {
      if (res.confirm) {
        uni.navigateBack()
      }
    }
  })
}

// 页面加载
onLoad((options) => {
  if (options?.id) {
    isEdit.value = true
    workOrderId.value = options.id
    console.log('编辑工单，ID:', workOrderId.value)
    // 这里可以加载工单详情
  } else {
    console.log('创建新工单')
  }
})

// 页面挂载
onMounted(() => {
  console.log('工单创建/编辑页面加载')
})
</script>

<style lang="scss" scoped>
.work-order-create-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
  padding: 24rpx;
  padding-bottom: 40rpx;
}

// 页面头部
.page-header {
  text-align: center;
  padding: 32rpx 0;

  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

// 表单区块
.form-section {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 24rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }

  .form-item {
    margin-bottom: 24rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .form-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
      margin-bottom: 12rpx;

      &.required::before {
        content: '*';
        color: #ff4d4f;
        margin-right: 4rpx;
      }
    }

    .form-input {
      width: 100%;
      height: 80rpx;
      padding: 0 24rpx;
      border: 2rpx solid #e8e8e8;
      border-radius: 12rpx;
      font-size: 28rpx;
      background: #fafafa;
      transition: all 0.3s ease;

      &:focus {
        border-color: #52c41a;
        background: #ffffff;
        box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.1);
      }
    }

    .form-textarea {
      width: 100%;
      min-height: 160rpx;
      padding: 24rpx;
      border: 2rpx solid #e8e8e8;
      border-radius: 12rpx;
      font-size: 28rpx;
      background: #fafafa;
      transition: all 0.3s ease;
      resize: vertical;

      &:focus {
        border-color: #52c41a;
        background: #ffffff;
        box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.1);
      }
    }

    .char-count {
      text-align: right;
      font-size: 24rpx;
      color: #999;
      margin-top: 8rpx;
    }
  }
}

// 单选按钮组
.radio-group {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;

  .radio-item {
    padding: 16rpx 24rpx;
    background: #f8f9fa;
    border: 2rpx solid #e8e8e8;
    border-radius: 24rpx;
    font-size: 26rpx;
    color: #666;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 8rpx;

    &.active {
      background: linear-gradient(135deg, #52c41a, #73d13d);
      color: #ffffff;
      border-color: #52c41a;
      box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.2);
    }

    &.priority {
      .priority-dot {
        width: 12rpx;
        height: 12rpx;
        border-radius: 50%;

        &.urgent {
          background: #ff4d4f;
        }

        &.high {
          background: #faad14;
        }

        &.medium {
          background: #1890ff;
        }

        &.low {
          background: #52c41a;
        }
      }
    }

    .radio-text {
      font-size: 26rpx;
    }
  }
}

// 设备选择器
.device-selector {
  .device-select {
    padding: 24rpx;
    border: 2rpx solid #e8e8e8;
    border-radius: 12rpx;
    background: #fafafa;
    transition: all 0.3s ease;

    &:active {
      background: #f5f5f5;
    }

    .selected-device {
      .device-name {
        display: block;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 8rpx;
      }

      .device-location {
        display: block;
        font-size: 26rpx;
        color: #666;
      }
    }

    .select-placeholder {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .placeholder-text {
        font-size: 28rpx;
        color: #999;
      }

      .placeholder-icon {
        font-size: 28rpx;
        color: #999;
        transform: rotate(90deg);
      }
    }
  }
}

// 时间输入组
.time-input-group {
  display: flex;
  align-items: center;
  gap: 16rpx;

  .time-input {
    flex: 1;
    max-width: 200rpx;
  }

  .time-unit {
    font-size: 28rpx;
    color: #666;
  }
}

// 标签输入容器
.tag-input-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  padding: 16rpx;
  border: 2rpx solid #e8e8e8;
  border-radius: 12rpx;
  background: #fafafa;
  min-height: 80rpx;
  align-items: center;

  .skill-tag,
  .material-tag {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 8rpx 16rpx;
    background: linear-gradient(135deg, #52c41a, #73d13d);
    color: #ffffff;
    border-radius: 20rpx;
    font-size: 24rpx;

    .tag-text {
      font-size: 24rpx;
    }

    .tag-remove {
      font-size: 24rpx;
      cursor: pointer;
      &:hover {
        opacity: 0.8;
      }
    }
  }

  .skill-input,
  .material-input {
    flex: 1;
    min-width: 200rpx;
    height: 48rpx;
    border: none;
    background: transparent;
    font-size: 28rpx;
    outline: none;

    &:focus {
      outline: none;
    }
  }
}

// 检查清单
.inspection-checklist {
  .checklist-item {
    display: flex;
    align-items: flex-start;
    gap: 16rpx;
    padding: 20rpx;
    background: #f8f9fa;
    border-radius: 12rpx;
    margin-bottom: 16rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .item-checkbox {
      flex-shrink: 0;
      padding: 4rpx;

      .checkbox-icon {
        font-size: 32rpx;
        color: #52c41a;
      }
    }

    .item-content {
      flex: 1;

      .item-name {
        display: block;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 8rpx;
      }

      .item-desc {
        display: block;
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

// 提交按钮
.form-actions {
  display: flex;
  gap: 24rpx;
  margin-top: 48rpx;

  .btn {
    flex: 1;
    height: 88rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
    font-weight: 500;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
    }

    .btn-text {
      font-size: 30rpx;
    }

    &.btn-primary {
      background: linear-gradient(135deg, #52c41a, #73d13d);
      color: #ffffff;
      box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);

      &.btn-disabled {
        background: #ccc;
        box-shadow: none;
        transform: none;
      }
    }

    &.btn-secondary {
      background: #ffffff;
      color: #52c41a;
      border: 2rpx solid #52c41a;
    }
  }
}
</style>